<!-- 创建直播间 -->
<template>
  <div id="LiveControlCreate">
    <c-title text="直播间"></c-title>
    <div class="box-main">
      <div class="field-box">
        <van-field v-model="title" :readonly="readonly" left-icon="edit" rows="1" autosize type="textarea" placeholder="6字以上的标题更能吸引人气哦" />
      </div>

      <div class="field-box">
        <van-cell :value="live_time ? live_time : '设置开播时间'" :readonly="readonly" is-link icon="clock-o" @click="showTimePop" />
      </div>

      <div class="field-box" v-if="pageConfig.cate || selectCate.name">
        <van-cell :value="selectCate.name ? selectCate.name : '选择直播间所属分类'" :readonly="readonly" is-link icon="shop-o" @click="showCategoryPop" />
      </div>

      <div class="flex">
        <van-uploader v-model="coverImg" :deletable="!readonly" use-before-read max-count="1" :after-read="afterReadCover" :delete="onDeleteCover">
          <div class="field-box img-wh-80 flex-column flex-a-c flex-j-c f-12 color-6E6E79 margin-right-10">
            <i class="iconfont icon-icon_add"></i>
            <div class="margin-top-6">上传封面</div>
          </div>
        </van-uploader>
        <template v-if="!readonly || (readonly && bannerImg.length)">
          <van-uploader v-model="bannerImg" :deletable="!readonly" use-before-read max-count="1" :after-read="afterReadBanner" :delete="onDeleteBanner">
            <div class="field-box img-wh-80 flex-column flex-a-c flex-j-c f-12 color-6E6E79 margin-right-10">
              <i class="iconfont icon-icon_add"></i>
              <div class="margin-top-6">上传横幅</div>
            </div>
          </van-uploader>
        </template>
      </div>

      <van-radio-group v-model="live_type" direction="horizontal" class="padding-tb-16" :disabled="readonly" checked-color="#ff3a93">
        <van-radio name="0" :disabled="true">手机直播</van-radio>
        <van-radio name="1" v-if="pageConfig.live_type">推流直播</van-radio>
      </van-radio-group>

      <template v-if="push_url && pageConfig.live_type">
        <div class="flex-j-sb margin-top-6" >
          <div class="f-14 color-000000 f-bold">推流地址</div>
          <div class="f-12 color-F15353" @click.stop v-clipboard:copy="push_url" v-clipboard:success="onCopy">复制</div>
        </div>
        <div class="f-12 color-6E6E79 t-l margin-top-6" style="overflow-wrap: break-word;">{{ push_url }}</div>
      </template>
    </div>

    <div class="box-main flex" style="padding: 12px 24px;">
      <div class="flex-column relative" v-if="!readonly" @click="toShowGoodPop">
        <i class="iconfont icon-aixinshangpin f-28"></i>
        <div class="margin-top-4 f-12">商品</div>
        <div class="f-12 good-num-tag">{{ selectedGoodList.length }}</div>
      </div>
      <div @click="showPurview = true" class="flex-column relative" style="margin-right: 32px;" v-if="readonly && pageConfig.purview">
        <i class="iconfont icon-guankanquanxian f-24"></i>
        <div class="margin-top-4 f-12">观看权</div>
      </div>
      <div class="flex-column relative" v-if="readonly" @click.stop="onCopyLiveURL">
        <i class="iconfont icon-fenxiang1 f-24"></i>
        <div class="margin-top-4 f-12">分享</div>
      </div>
    </div>

    <div class="fixed-bottom padding-10 flex set-pc-styleLeft">
      <!-- <van-button @click="toBack" type="primary" plain block round color="#FF3737" style="width: 160px;margin-right: 10px;">返回</van-button> -->
      <van-button v-if="liveStatus == -1" @click.stop="creatRoom" type="primary" block round color="linear-gradient(to right, #FF3A93, #FF3737)">创建直播间</van-button>
      <van-button v-if="liveStatus == 2" @click.stop="startLive" type="primary" block round color="linear-gradient(to right, #FF3A93, #FF3737)">
        <!-- 等待直播 -->
        <div v-if="CountDownTime">
          距离开播还剩：
          <van-count-down :time="CountDownTime" format="DD 天 HH 时 mm 分 ss 秒" style="color: #fff;" />
        </div>
        <div v-if="!CountDownTime">开始直播</div>
      </van-button>
      <van-button v-if="liveStatus == 3" @click.stop="endLive" type="primary" block round color="linear-gradient(to right, #FF3A93, #FF3737)">
        结束直播
      </van-button>
    </div>

    <van-popup v-model="showTime" class="pop-base-class" position="bottom" round>
      <van-datetime-picker v-model="currentDate" @confirm="confirmTime" @cancel="showTime = false" type="datetime" title="选择完整时间" :min-date="minDate" :max-date="maxDate" />
    </van-popup>

    <van-popup v-model="showCategory" class="pop-base-class t-l" position="bottom" round style="background-color: #F5F5F5;" closeable>
      <div class="pop-base-title">选择直播间分类</div>
      <div class="pop-base-content">
        <van-radio-group v-model="selectCate">
          <van-cell-group>
            <van-cell :title="item.name" clickable data-index="index" @click="selectCate = item" v-for="(item, index) in categoryList" :key="item.id">
              <template #right-icon>
                <van-radio :name="item" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div class="pop-base-bottom" @click.stop="showCategory = false">
        <van-button round type="danger" color="var(--themeBaseColor)" block style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showGood" class="pop-base-class t-l" position="bottom" round closeable>
      <div class="pop-base-title" style="margin-bottom: 0!important;">选择商品</div>
      <div class="flex bg-fff">
        <div class="margin-left-10 flex-a-c">
          <van-popover v-model="showPopover" trigger="click" :actions="actions" placement="right-start" @select="onSelectPopover">
            <template #reference>
              <div class="flex-a-c">
                <div class="f-13">{{ role.text + "商品" || "请选择角色" }}</div>
                <i class="iconfont icon-icon_down1 f-12"></i>
              </div>
            </template>
          </van-popover>
        </div>
        <div class="f-grow-1">
          <van-search v-model="goodKeyword" @search="onSearchGood" placeholder="请输入关键字进行搜索" clearable shape="round"></van-search>
        </div>
      </div>

      <div style="background-color: #F5F5F5;padding-top: 0.5rem;">
        <van-cell-group inset style="margin:0 12px 8px;">
          <van-cell v-if="role && role.id" :title="`当前${role.text}`" :value="goodSelectStore.store_name || '请选择'" @click="toSelectStore" icon="shop-o" is-link />
          <van-cell title="# 当前分类" :value="selectedCateName || '全部'" is-link @click="toSelectCate" />
        </van-cell-group>

        <div class="pop-base-content" style="max-height: 55vh;">
          <van-checkbox-group v-model="selectedGoodList">
            <van-cell-group>
              <van-cell v-for="(item, index) in goodList" clickable :key="item" @click="toggleGoodList(index)">
                <template #icon>
                  <van-checkbox :name="item" ref="checkboxes" checked-color="var(--themeBaseColor)" />
                </template>
                <template #default>
                  <div class="flex good-item">
                    <div class="good-item-img">
                      <img :src="item.thumb" />
                    </div>
                    <div class="f-grow-1 flex-column flex-j-sb margin-left-10">
                      <div class="f-14 color-000 f-bold line-clamp-2 good-item-title">{{ item.title }}</div>
                      <div class="f-12 color-999 good-item-award flex">
                        <div class="tag-box f-12">佣金: ¥{{ item.award }}</div>
                      </div>
                      <div class="flex-j-sb flex-a-c">
                        <div class="f-16 flex-a-c f-bold themeColor">
                          <div class="f-12">￥</div>
                          <div>{{ item.price }}</div>
                        </div>
                        <div class="flex-a-c" @click.stop v-if="pageConfig.recommend_goods">
                          <div class="f-13 margin-right-6 color-999999">推荐</div>
                          <van-switch :value="is_recommend[item.id]" @input="onRecommendSwitch($event, item.id, index)" size="18px" active-color="var(--themeBaseColor)" inactive-color="#f5f5f5" />
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>
      </div>
      <div class="pop-base-bottom" @click.stop="showGood = false">
        <van-button round type="danger" color="var(--themeBaseColor)" block style="height: 40px;">选完了，返回直播间</van-button>
      </div>
      <div class="fixed-goodBox" @click.stop="showHasGoodPop = true">
        <i class="iconfont icon-a-ht_basis_shangpin_huaban1_huaban1 f-24"></i>
      </div>
    </van-popup>

    <van-popup v-model="showHasGoodPop" class="pop-base-class t-l" position="bottom" round style="background-color: #F5F5F5;">
      <div class="pop-base-title">编辑已选择商品</div>
      <div class="pop-base-content">
        <van-cell-group>
          <van-cell v-for="(item, index) in selectedGoodList" clickable :key="item">
            <template #default>
              <div class="flex good-item" style="margin: 0;">
                <div class="good-item-img">
                  <img :src="item.thumb" />
                </div>
                <div class="f-grow-1 flex-column flex-j-sb margin-left-10">
                  <div class="f-14 color-000 f-bold line-clamp-2 good-item-title">{{ item.title }}</div>
                  <div class="f-12 color-999 good-item-award flex">
                    <div class="tag-box f-12">佣金: ¥{{ item.award }}</div>
                  </div>
                  <div class="flex-j-sb flex-a-c">
                    <div class="f-16 flex-a-c f-bold themeColor">
                      <div class="f-12">￥</div>
                      <div>{{ item.price }}</div>
                    </div>
                    <div class="flex-a-c" @click.stop>
                      <template v-if="pageConfig.recommend_goods">
                        <div class="f-13 margin-right-6 color-999999">推荐</div>
                        <van-switch :value="is_recommend[item.id]" @input="onRecommendSwitch($event, item.id)" size="18px" active-color="var(--themeBaseColor)" inactive-color="#f5f5f5" />
                      </template>
                      <van-icon @click.stop="onDelGoodList(index)" name="delete-o" size="22" class="margin-left-6" />
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      <div class="pop-base-bottom flex">
        <van-button @click.stop="onClearSelectGood" round plain type="danger" color="var(--themeBaseColor)" block style="width: 100px; height: 40px;margin-right: 10px;">清空</van-button>
        <van-button @click.stop="showHasGoodPop = false" round type="danger" color="var(--themeBaseColor)" block style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showStore" class="pop-base-class t-l" position="bottom" round style="background-color: #F5F5F5;">
      <div class="pop-base-title">选择{{ role.text }}</div>
      <div class="pop-base-content">
        <van-radio-group v-model="goodSelectStore">
          <van-cell-group>
            <van-cell :title="item.store_name" clickable data-index="index" @click="goodSelectStore = item" v-for="(item, index) in storeList" :key="item.id">
              <template #right-icon>
                <van-radio :name="item" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div class="pop-base-bottom" @click.stop="onChangeSelectStore">
        <van-button round type="danger" color="var(--themeBaseColor)" block style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

    <van-popup v-model="showCateCascader" closeable round position="bottom">
      <van-cascader v-model="cateCascaderValue" title="请选择分类" :options="goodCategory" :field-names="cateCascaderNames" @close="showCateCascader = false" @finish="onFinishCateCascader" />
    </van-popup>

    <van-popup v-model="showPurview" closeable class="pop-base-class t-l" position="bottom" round style="background-color: #F5F5F5;">
      <div class="pop-base-title">设置观看权限</div>
      <div class="pop-base-content" style="min-height: 60vh;max-height: 75vh;">
        <van-cell-group>
          <van-field name="switch" label="会员观看权限" input-align="right">
            <template #input>
              <van-switch v-model="is_purview" size="20" active-color="var(--themeBaseColor)" />
            </template>
          </van-field>
        </van-cell-group>
        <div v-show="is_purview" class="margin-top-10">
          <van-collapse v-model="activeCollapse" :accordion="true" :border="false">
            <van-collapse-item name="1" v-if="purviewInfo.member_level_open">
              <template #title>
                <div class="flex-a-c"><van-checkbox v-model="checkedMemberLevel.length" :disabled="true" checked-color="var(--themeBaseColor)" class="margin-right-10"></van-checkbox>会员等级</div>
              </template>
              <van-checkbox-group v-model="checkedMemberLevel">
                <van-cell-group>
                  <van-cell v-for="(item, index) in purviewInfo.member_level" clickable :key="item" :title="item.name" style="background: #F5F5F5;">
                    <template #icon>
                      <van-checkbox :name="item.id" class="margin-right-10" checked-color="var(--themeBaseColor)" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </van-collapse-item>
            <van-collapse-item name="2" v-if="purviewInfo.commission_level_open">
              <template #title>
                <div class="flex-a-c">
                  <van-checkbox v-model="checkedCommissionLevel.length" :disabled="true" checked-color="var(--themeBaseColor)" class="margin-right-10"></van-checkbox>分销商等级
                </div>
              </template>
              <van-checkbox-group v-model="checkedCommissionLevel">
                <van-cell-group>
                  <van-cell v-for="(item, index) in purviewInfo.commission_level" clickable :key="item" :title="item.name" style="background: #F5F5F5;">
                    <template #icon>
                      <van-checkbox :name="item.id" class="margin-right-10" checked-color="var(--themeBaseColor)" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </van-collapse-item>
            <van-collapse-item name="2" v-if="purviewInfo.team_level_open">
              <template #title>
                <div class="flex-a-c">
                  <van-checkbox v-model="checkedCommissionLevel.length" :disabled="true" checked-color="var(--themeBaseColor)" class="margin-right-10"></van-checkbox>分销商等级
                </div>
              </template>
              <van-checkbox-group v-model="checkedTeamLevel">
                <van-cell-group>
                  <van-cell v-for="(item, index) in purviewInfo.team_level" clickable :key="item" :title="item.name" style="background: #F5F5F5;">
                    <template #icon>
                      <van-checkbox :name="item.id" class="margin-right-10" checked-color="var(--themeBaseColor)" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </van-collapse-item>
          </van-collapse>
          <van-cell-group>
            <van-cell v-if="purviewInfo.agent_open" clickable title="推广员">
              <template #icon>
                <van-checkbox v-model="agent" class="margin-right-10" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
            <van-cell v-if="purviewInfo.store_open" clickable title="门店店长">
              <template #icon>
                <van-checkbox v-model="store" class="margin-right-10" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
            <van-cell v-if="purviewInfo.hotel_open" clickable title="酒店店长">
              <template #icon>
                <van-checkbox v-model="hotel" class="margin-right-10" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
            <van-cell v-if="purviewInfo.supplier_open" clickable title="供应商">
              <template #icon>
                <van-checkbox v-model="supplier" class="margin-right-10" checked-color="var(--themeBaseColor)" />
              </template>
            </van-cell>
          </van-cell-group>
        </div>

        <van-cell-group v-show="is_purview" class="margin-top-10" :border="false">
          <van-field name="switch" label="密码访问" input-align="right">
            <template #input>
              <van-switch v-model="password_open" size="20" active-color="var(--themeBaseColor)" />
            </template>
          </van-field>
          <van-field v-show="password_open" v-model="password" label="设置密码" placeholder="请设置访问密码" />
        </van-cell-group>
      </div>
      <div class="pop-base-bottom" @click.stop="subSetPurview">
        <van-button round type="danger" color="var(--themeBaseColor)" block style="height: 40px;">保存</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Cascader } from "vant";
Vue.use(Cascader);
export default {
  data() {
    return {
      liveStatus: -1,
      CountDownTime: 0,
      readonly: false,
      push_url: "",
      pageConfig: {},
      title: "",
      live_time: "",
      banner: "",
      live_type: '1',

      showTime: false,
      minDate: new Date(),
      maxDate: new Date(2028, 11, 15),
      currentDate: new Date(),

      showCategory: false,
      selectCate: {},
      categoryList: [],

      coverImg: [],
      bannerImg: [],

      showGood: false,
      goodList: [],
      goodSelect: [],

      showPopover: false,
      role: {},
      actions: [],
      goodKeyword: "",

      goodSelectStore: {},
      showStore: false,
      storeList: [],

      goodCategory: [],
      selectedCateName: "",
      showCateCascader: false,
      cateCascaderValue: [],
      cateCascaderNames: {
        text: "name",
        value: "id",
        children: "childrens"
      },

      selectedGoodList: [],
      showHasGoodPop: false,
      is_recommend: {},

      purviewInfo: {},
      showPurview: false,
      is_purview: 0,
      activeCollapse: [],

      checkedMemberLevel: [],
      checkedCommissionLevel: [],
      checkedTeamLevel: [],
      agent: 0,
      store: 0,
      hotel: 0,
      supplier: 0,
      password_open: 0,
      password: ""
    };
  },

  activated() {
    this.init();
    if (this.$route.params.id) {
      // 直播间开播
      this.readonly = true;
      this.getLiveRoomInfo();
      this.getPurviewInfo();
    } else {
      this.actions = [];
    }
    this.getRolelist();
  },

  components: {},

  computed: {},

  mounted() {},

  methods: {
    init() {
      this.coverImg = [];
      this.bannerImg = [];

    },
    confirmTime() {
      this.showTime = false;
      this.live_time =
        this.currentDate.getFullYear() + "/" + (this.currentDate.getMonth() + 1) + "/" + this.currentDate.getDate() + " " + this.currentDate.getHours() + ":" + this.currentDate.getMinutes();
    },
    async getLiveRoomInfo() {
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.member.live-one",
        {
          room_id: this.$route.params.id
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.live_time_commit = data.live_time;
      this.title = data.title;
      this.liveStatus = data.status;
      if (data.cover) this.coverImg.push({ url: data.cover });
      if (data.banner) this.bannerImg.push({ url: data.banner });
      this.live_time = this.fun.timestampToTime(data.live_time);
      this.CountDownTime = this.fun.getTimeDifference(this.fun.getTimestamp(data.live_time));
      this.selectCate.name = data.cate_name;
      this.push_url = data.url;
      this.live_type = data.live_type + '';
    },
    async startLive() {
      if(this.live_type == 0 || this.pageConfig.live_type == 0) return this.$toast.fail("暂不支持手机直播，请使用app端直播");
      this.CountDownTime = this.fun.getTimeDifference(this.fun.getTimestamp(this.live_time_commit));
      if (this.CountDownTime) return this.$toast.fail("直播时间未到");

      this.$dialog
        .confirm({
          message: "确定开始直播吗？"
        })
        .then(() => {
          $http
            .post(
              "plugin.room.frontend.member.start-live",
              {
                room_id: this.$route.params.id
              },
              "."
            )
            .then(({ result, msg }) => {
              this.$toast(msg);
              if (result == 1) {
                this.liveStatus = 3;
              }
            });
        });
    },
    endLive() {
      this.$dialog
        .confirm({
          message: "确定结束直播吗？"
        })
        .then(() => {
          $http
            .post(
              "plugin.room.frontend.member.end-live",
              {
                room_id: this.$route.params.id
              },
              "."
            )
            .then(({ result, msg }) => {
              this.$toast(msg);
              if (result == 1) {
                this.$router.push(this.fun.getUrl("LiveControlHome"));
              }
            });
        });
    },
    async showCategoryPop() {
      if (this.readonly) return;
      if (this.categoryList.length) return (this.showCategory = true);
      let { result, msg, data } = await $http.post("plugin.room.frontend.create-live.get-room-category", {}, ".");
      if (result == 0) return this.$toast(msg);
      this.categoryList = data;
      this.selectCate = data[0];
      this.showCategory = true;
    },
    onSelectPopover(action) {
      this.role = action;
      this.storeList = [];
      this.goodSelectStore = {};
      this.goodCategory = [];
      this.selectedCateName = "";
      this.cateCascaderValue = [];
      this.goodList = [];
      this.goodKeyword = "";
      this.showPopover = false;
      if (this.role.id !== 0) {
        this.toSelectStore();
      }
    },
    showTimePop() {
      if (this.readonly) return;
      this.showTime = true;
    },
    toShowGoodPop() {
      if (!this.goodList.length) this.getGoodList();
      this.showGood = true;
    },

    onSearchGood() {
      this.getGoodList();
    },
    onChangeSelectStore() {
      this.goodCategory = [];
      this.selectedCateName = "";
      this.cateCascaderValue = [];
      this.showStore = false;
      this.getGoodList();
    },

    async toSelectStore() {
      if (this.storeList.length) return (this.showStore = true);
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.create-live.role-check",
        {
          role_id: this.role.id
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.storeList = data;
      this.showStore = true;
      this.goodCategory = [];
      this.selectedCateName = "";
      this.cateCascaderValue = [];
      this.goodSelectStore = data[0];
    },
    async getGoodcategory() {
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.create-live.get-category",
        {
          role_id: this.role.id,
          shop_id: this.goodSelectStore.id
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.goodCategory = data.list;
      this.cateCascaderValue = [];
      this.selectedCateName = "";
      this.showCateCascader = true;
    },
    toSelectCate() {
      if (this.role.id !== 0 && !this.goodSelectStore.id) {
        this.$toast.fail(`请先选择商品所属${this.role.text}`);
        return;
      }
      if (this.goodCategory.length) return (this.showCateCascader = true);
      if (!this.goodCategory.length) {
        this.getGoodcategory();
      }
    },
    onFinishCateCascader({ selectedOptions }) {
      this.showCateCascader = false;
      this.cateCascaderValue = selectedOptions;
      let cate = this.cateCascaderValue.map(item => item.name).join("/");
      this.selectedCateName = cate;
      this.getGoodList();
    },
    async getGoodList() {
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.create-live.get-goods",
        {
          role_id: this.role.id,
          shop_id: this.goodSelectStore.id,
          cate_id: this.cateCascaderValue.length > 0 ? this.cateCascaderValue[this.cateCascaderValue.length - 1].id : 0,
          keyword: this.goodKeyword,
          page: 1
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.goodList = data;
      this.showStore = false;
      this.showGood = true;
    },
    async getRolelist() {
      let { result, msg, data } = await $http.post("plugin.room.frontend.create-live.role", {}, ".");
      if (result == 0) return this.$toast(msg);
      // 角色，0商城，1门店，2供应商，3酒店
      this.actions.push({ text: "平台", id: 0 });
      if (data.store) this.actions.push({ text: "门店", id: 1 });
      if (data.supplier) this.actions.push({ text: "供应商", id: 2 });
      if (data.hotel) this.actions.push({ text: "酒店", id: 3 });
      this.role = this.actions[0];
      this.pageConfig = data;
      if(this.pageConfig.live_type == 0) {
        return this.$toast.fail("暂不支持创建直播间，请联系后台开启推流地址");
      }
    },
    toggleGoodList(index) {
      this.$refs.checkboxes[index].toggle();
      this.$nextTick(() => {
        setTimeout(() => {
          let checked = this.$refs.checkboxes[index].checked;
          let item = this.goodList[index];
          // let is_recommend_length = Object.keys(this.is_recommend).length; // 获取this.is_recommend对象长度
          let is_recommend_item = this.is_recommend[item.id]; // 获取this.is_recommend对象的值
          if (!checked && is_recommend_item) {
            delete this.is_recommend[item.id];
            this.$forceUpdate();
          }
        }, 500);
      });
    },
    onRecommendSwitch(e, id, index = null) {
      // 获取this.is_recommend对象长度
      if (index != null && this.$refs.checkboxes[index]) {
        let checked = this.$refs.checkboxes[index].checked;
        if (!checked) {
          this.$toast.fail("请先选择该商品");
          return;
        }
      }
      let length = Object.keys(this.is_recommend).length;
      if (!e) {
        delete this.is_recommend[id];
      } else if (length >= 2) {
        this.$toast.fail("最多只能选择两个推荐商品"); // 如果this.is_recommend对象长度大于等于2，禁止切换
      } else if (e) {
        this.is_recommend[id] = true; // 如果this.is_recommend对象长度小于2，允许切换
      }
      this.$forceUpdate();
    },
    onDelGoodList(index) {
      // 删除已选择商品,selectedGoodList删除下标index
      let item = this.selectedGoodList[index];
      if (this.is_recommend[item.id]) {
        delete this.is_recommend[item.id];
        this.$forceUpdate();
      }
      this.selectedGoodList.splice(index, 1);
    },
    onClearSelectGood() {
      this.selectedGoodList = [];
      this.is_recommend = {};
      this.$forceUpdate();
    },

    creatRoom() {
      if(this.pageConfig.live_type == 0) {
        return this.$toast.fail("暂不支持创建直播间，请联系后台开启推流地址");
      }
      if (!this.title) {
        this.$toast("请输入标题");
        return;
      }
      if (!this.cover) {
        this.$toast("请上传封面");
        return;
      }
      if (!this.live_time) {
        this.$toast("请选择开播时间");
        return;
      }
      if (this.pageConfig.cate && !this.selectCate.id) {
        this.$toast("请选择直播间分类");
        return;
      }
      //获取selectedGoodList里的id并用逗号拼接
      let _selectedGoodList = this.selectedGoodList.map(item => item.id).join(",");
      let _is_recommend = Object.keys(this.is_recommend)
        .map(item => item)
        .join(",");
      let params = {
        title: this.title,
        live_time: this.currentDate.getTime(),
        cover: this.cover,
        banner: this.banner,
        goods: _selectedGoodList,
        cate_id: this.selectCate.id,
        role_id: this.role.id,
        shop_id: this.goodSelectStore.id,
        is_recommend: _is_recommend,
        live_type: 1
      };

      $http.post("plugin.room.frontend.create-live.create", params, "正在创建直播间").then(({ result, msg }) => {
        this.$toast(msg);
        if (result == 1) {
          this.$router.replace(this.fun.getUrl("LiveControlHome"));
        }
      });
    },
    async getPurviewInfo() {
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.create-live.get-purview",
        {
          room_id: this.$route.params.id
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.purviewInfo = data;
      this.is_purview = data.is_purview ? true : false;
      //member_level 获取check为1的id
      if (data.member_level) this.checkedMemberLevel = data.member_level.filter(item => item.check == 1).map(item => item.id);
      //commission_level 获取check为1的id
      if (data.commission_level) this.checkedCommissionLevel = data.commission_level.filter(item => item.check == 1).map(item => item.id);
      //team_level 获取check为1的id
      if (data.team_level) this.checkedTeamLevel = data.team_level.filter(item => item.check == 1).map(item => item.id);

      this.agent = data.agent_check ? true : false;
      this.store = data.store_check ? true : false;
      this.hotel = data.hotel_check ? true : false;
      this.supplier = data.supplier_check ? true : false;
      this.password_open = data.password_open ? true : false;
      this.password = data.password;
    },
    async subSetPurview() {
      let purview = {
        member_level: this.checkedMemberLevel,
        commission_level: this.checkedCommissionLevel,
        team_level: this.checkedTeamLevel,
        agent: this.agent,
        store: this.store,
        hotel: this.hotel,
        supplier: this.supplier,
        password_open: this.password_open,
        password: this.password
      };
      let { result, msg, data } = await $http.post(
        "plugin.room.frontend.create-live.set-purview",
        {
          room_id: this.$route.params.id,
          is_purview: this.is_purview,
          purview: purview
        },
        "."
      );
      this.$toast(msg);
      if (result == 1) {
        this.showPurview = false;
      }
    },
    // 复制链接
    onCopy() {
      this.$toast.success('复制成功');
    },
    onCopyLiveURL() {
      let desc = "邀请您加入直播间：" + this.title + "\n";
      let link = `${this.fun.getSiteRoot()}/addons/yun_shop/?menu#/livePage?i=${this.fun.getKeyByI()}&mid=${this.fun.getKeyByMid()}&shareType=livePlay&room_id=${this.$route.params.id}`;
      this.$copyText(`${desc}${link}`).then(
        e => {
          this.$toast("复制成功");
        },
        e => {
          this.$toast("复制失败");
        }
      );
    },

    afterReadCover(file) {
      let uploadLoading = this.$toast.loading({
        message: "上传中",
        duration: 0
      });

      let fd = new FormData();
      fd.append("file", file.file);

      axios
        .post(this.fun.getRealUrl("upload.uploadPic"), fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(({ data }) => {
          if (data.result == 1) {
            this.cover = data.data.img;
          } else {
            this.coverImg = [];
          }
          uploadLoading.clear();
        })
        .catch(() => {
          this.$toast("上传失败");
          uploadLoading.clear();
        });
    },
    onDeleteCover() {
      this.coverImg = [];
    },
    afterReadBanner(file) {
      let uploadLoading = this.$toast.loading({
        message: "上传中",
        duration: 0
      });

      let fd = new FormData();
      fd.append("file", file.file);

      axios
        .post(this.fun.getRealUrl("upload.uploadPic"), fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(({ data }) => {
          if (data.result == 1) {
            this.banner = data.data.img;
          } else {
            this.bannerImg = [];
          }
          uploadLoading.clear();
        })
        .catch(() => {
          this.$toast("上传失败");
          uploadLoading.clear();
        });
    },
    onDeleteBanner() {
      this.bannerImg = [];
    },
    toBack() {
      try {
        this.$router.go(-1);
      } catch (e) {
        this.$router.push(this.fun.getUrl("home", {}));
      }
    },
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.pop-base-title {
  margin: 18px 12px 12px !important;
  font-size: 1rem !important;
  font-weight: bold !important;
  text-align: left !important;
}
.pop-base-class .pop-base-content {
  min-height: 39vh;
  max-height: 60vh;
  overflow: scroll;
  padding: 0 0.75rem 3.75rem;
}
.pop-base-class .pop-base-bottom {
  padding: 0.625rem 0.875rem;
  background: #ffffff;
}
.relative {
  position: relative;
}
.color-F15353 {
  color: #f15353;
}
.padding-tb-16 {
  padding: 1rem 0;
}
#LiveControlCreate {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(200deg, #c9dcfe 0%, #ded0f1 30%, #f5f5f5 100%);
}
.box-main {
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px 12px 12px 12px;
  padding: 12px;
  margin-bottom: 10px;
  .good-num-tag {
    position: absolute;
    top: -0.5rem;
    right: -0.5rem;
    padding: 0 0.375rem;
    background: #ff3a93;
    color: #fff;
    border-radius: 0.5rem;
    text-align: center;
    line-height: 1.125rem;
  }
}
.field-box {
  border-radius: 24px;
  overflow: hidden;
  margin-bottom: 12px;
  background: #fff;
}
.img-wh-80 {
  width: 80px;
  height: 80px;
  margin: 0;
  border-radius: 12px;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
.fixed-bottom {
  position: fixed;
  bottom: 3rem;
  left: 0;
  right: 0;
}
.good-item {
  margin-left: 0.375rem;
  .good-item-img {
    width: 5.375rem;
    height: 5.375rem;
    border-radius: 0.5rem;
    overflow: hidden;
    flex-shrink: 0;
    img {
      width: 100%;
      height: 100%;
      display: block;
      object-fit: contain;
    }
  }
  .good-item-title {
    line-height: 1.125rem;
  }
  .tag-box {
    line-height: 18px;
    padding: 0 0.375rem;
    border-radius: 4px 4px 4px 4px;
    background: #fff0e8;
    color: #f96d20;
  }
}
.fixed-goodBox {
  position: fixed;
  bottom: 8rem;
  right: 0.5rem;
  width: 3.125rem;
  height: 3.125rem;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  box-shadow: 0px 2px 8px rgba(255, 255, 255, 0.25);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ffffff;
}
</style>
